# pythonProject5/api/v1/routes/transcribe.py

from fastapi import APIRouter, UploadFile, File, HTTPException, Depends
from typing import Dict
import shutil
import os
import uuid
from pathlib import Path
from sqlalchemy.orm import Session

from core.asr_engine import asr_engine
from db.session import get_db_session
from models.db import ASRRecord
from api.v1.auth import get_current_user
from pydantic import BaseModel

router = APIRouter(tags=["Transcribe"])

UPLOAD_DIR = "uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)

class TranscriptionResponse(BaseModel):
    filename: str
    text: str
    language: str
    duration_seconds: int
    file_size: int

@router.post("/", response_model=TranscriptionResponse)
async def transcribe_audio(
    audio_file: UploadFile = File(...),
    current_user = Depends(get_current_user),
    db: Session = Depends(get_db_session)
):
    """
    上传音频文件并返回识别结果。
    支持格式: MP3, WAV, OGG, WebM 等。
    """
    # 1. 检查文件类型
    if not audio_file.content_type or not audio_file.content_type.startswith("audio/"):
        raise HTTPException(status_code=400, detail="只支持音频文件")

    # 2. 生成唯一文件名
    ext = Path(audio_file.filename).suffix or ".webm"
    safe_filename = f"{uuid.uuid4().hex}{ext}"
    file_path = os.path.join(UPLOAD_DIR, safe_filename)

    # 3. 保存文件
    try:
        with open(file_path, "wb") as f:
            shutil.copyfileobj(audio_file.file, f)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件保存失败: {e}")

    # 4. ASR 识别
    try:
        result = asr_engine.transcribe(Path(file_path))
        text = result.get("text", "").strip()
        lang = result.get("detected_language", "unknown")
        duration = result.get("duration", 0.0)  # 假设返回 float（秒）
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"语音识别失败: {e}")

    # 5. 文件大小
    try:
        file_size = os.path.getsize(file_path)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文件大小失败: {e}")

    # 6. 正确保存到 ASRRecord 表
    asr_record = ASRRecord(
        user_id=current_user.id,
        audio_path=file_path,           # 正确字段
        filename=audio_file.filename,   # 原始文件名
        text=text,
        language=lang,
        duration_seconds=int(duration), # duration_seconds 是整数字段
        file_size=file_size,
        model_used="whisper"            # 可选：根据 asr_engine 填写
    )

    try:
        db.add(asr_record)
        db.commit()
        db.refresh(asr_record)
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"数据库保存失败: {str(e)}")

    return {
        "filename": audio_file.filename,
        "text": text,
        "language": lang,
        "duration_seconds": int(duration),
        "file_size": file_size
    }